package com.deyou.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.deyou.AppManager;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.LzyResponse;
import com.deyou.model.SimpleResponse;
import com.deyou.model.UserInfoBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.Logger;
import com.deyou.util.MD5Util;
import com.deyou.util.Urls;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RegistActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_phone_label)
    ImageView ivPhoneLabel;
    @BindView(R.id.phone_regist_layout)
    RelativeLayout phoneRegistLayout;
    @BindView(R.id.iv_mail_label)
    ImageView ivMailLabel;
    @BindView(R.id.mail_regist_layout)
    RelativeLayout mailRegistLayout;
    @BindView(R.id.regist_header_layout)
    RelativeLayout registHeaderLayout;
    @BindView(R.id.tv_phone_title)
    TextView tvPhoneTitle;
    @BindView(R.id.tv_phone_area_code)
    TextView tvPhoneAreaCode;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.phone_layout)
    RelativeLayout phoneLayout;
    @BindView(R.id.tv_mail_title)
    TextView tvMailTitle;
    @BindView(R.id.et_mail)
    EditText etMail;
    @BindView(R.id.mail_layout)
    RelativeLayout mailLayout;
    @BindView(R.id.tv_pwd_title)
    TextView tvPwdTitle;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.ic_nosee_pwd)
    ImageView icNoseePwd;
    @BindView(R.id.password_layout)
    RelativeLayout passwordLayout;
    @BindView(R.id.btn_regist)
    TextView btnRegist;
    @BindView(R.id.tv_regist_rule)
    TextView tvRegistRule;
    @BindView(R.id.btn_goto_login)
    TextView btnGotoLogin;
    private boolean flag;

    private int userRegisterType = 2; // 1-手机注册（已隐藏） 2-邮箱注册（默认）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_regist);
        ButterKnife.bind(this);
        flag = true;
        userRegisterType = 2;
    }

    @Override
    protected boolean translucentStatusBar() {
        return super.translucentStatusBar();
    }

    @OnClick({R.id.iv_back, R.id.phone_regist_layout, R.id.mail_regist_layout, R.id.tv_phone_area_code, R.id.ic_nosee_pwd, R.id.btn_regist, R.id.btn_goto_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.phone_regist_layout:
                ivPhoneLabel.setVisibility(View.VISIBLE);
                ivMailLabel.setVisibility(View.GONE);
                mailLayout.setVisibility(View.GONE);
                phoneLayout.setVisibility(View.VISIBLE);
                registHeaderLayout.setBackgroundResource(R.drawable.bg_phone_regist);
                etPassword.setText("");
                userRegisterType = 1;
                break;
            case R.id.mail_regist_layout:
                ivPhoneLabel.setVisibility(View.GONE);
                ivMailLabel.setVisibility(View.VISIBLE);
                mailLayout.setVisibility(View.VISIBLE);
                phoneLayout.setVisibility(View.GONE);
                registHeaderLayout.setBackgroundResource(R.drawable.bg_mail_regist);
                etPassword.setText("");
                userRegisterType = 2;
                break;
            case R.id.tv_phone_area_code:
                break;
            case R.id.ic_nosee_pwd:
                if (TextUtils.isEmpty(etPassword.getText().toString().trim()))
                    return;
                if (flag == true) {
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    flag = false;
                    icNoseePwd.setImageResource(R.drawable.ic_see_pwd);
                } else {
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    flag = true;
                    icNoseePwd.setImageResource(R.drawable.ic_nosee_pwd);
                }
                etPassword.setSelection(etPassword.getText().length());
                break;
            case R.id.btn_regist:
                if (1 == userRegisterType){
                    if (TextUtils.isEmpty(etPhone.getText().toString().trim())){
                        showToast("注册手机号不能为空");
                        return;
                    }
                } else if (2 == userRegisterType){
                    if (TextUtils.isEmpty(etMail.getText().toString().trim())){
                        showToast("注册邮箱不能为空");
                        return;
                    }
                }
                if (TextUtils.isEmpty(etPassword.getText().toString().trim())){
                    showToast("注册密码不能为空");
                    return;
                }
                registIntoApp();
                break;
            case R.id.btn_goto_login:
                AndroidUtils.startNextActivity(this, LoginActivity.class, null, false);
                AppManager.getAppManager().finishAllActivity(LoginActivity.class);
                break;
        }
    }

    private void registIntoApp() {
        final Bundle b = new Bundle();
        final Message msg = new Message();
        JSONObject object = new JSONObject();
        try {
            object.put("userLogin", userRegisterType == 1 ? etPhone.getText().toString().trim() : etMail.getText().toString().trim());
            object.put("userPassword", etPassword.getText().toString().trim());
            object.put("userRegisterType", userRegisterType);
            String paramJson = object.toString();


            ServerApi.getString(Urls.register, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading();
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull String s) {
                            SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                            if (null != resp){
                                b.putString("errMsg", resp.msg);
                                if (resp.code == 1){
                                    b.putInt("code", 1);
                                } else {
                                    b.putInt("code", 2);
                                }
                                msg.setData(b);
                                handler.sendMessage(msg);
                            } else {
                                b.putInt("code", 3);
                                msg.setData(b);
                                handler.sendMessage(msg);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            b.putInt("code", 3);
                            msg.setData(b);
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.getData().getInt("code");
            switch (code){
                case 1:
                    showToast("注册成功,请登录");
                    AndroidUtils.startNextActivity(RegistActivity.this, LoginActivity.class, null, false);
                    AppManager.getAppManager().finishAllActivity(LoginActivity.class);
                    registIntoJChat(etMail.getText().toString(), etPassword.getText().toString());
                    break;
                case 2:
                    String errMsg = msg.getData().getString("errMsg");
                    showToast(errMsg);
                    break;
                case 3:
                    showToast("注册失败");
                    break;
            }
        }
    };

    /**
     * 用户在极光注册
     */
    private void registIntoJChat(String userName, String pwd){
        JMessageClient.register("DeYou"+"_"+ userName.split("@")[0], MD5Util.md5(pwd), new BasicCallback() {
            @Override
            public void gotResult(final int status, String desc) {
                if (status == 0) {
                    Logger.i("DeYou-JChat", "JChat注册成功");
                } else {
                    Logger.i("DeYou-JChat", desc);
                }
            }
        });
    }
}
